import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/', // 网页打开第一次默认路径就是'/'
    /* redirect: '/login' */
    component: () => import('@/views/layout'), // 默认打开布局页
    redirect: '/home', // 路由再次匹配
    children: [
      {
        path: 'home',
        component: () => import('@/views/home')
      },
      {
        path: 'user-info', // 这里必须叫user-info, 因为侧边栏导航切换的是它
        component: () => import('@/views/user/userInfo')
      },
      {
        path: 'user-avatar', // 必须用这个值
        component: () => import('@/views/user/userAvatar')
      },
      {
        path: 'user-pwd', // 必须用这个值
        component: () => import('@/views/user/userPwd')
      },
      {
        path: 'art-list1', // 防疫手册
        component: () => import('@/views/article/artList1')
      },
      {
        path: 'art-list2', // 防疫手册
        component: () => import('@/views/article/artList2')
      },
      {
        path: 'art-list3', // 防疫手册
        component: () => import('@/views/article/artList3')
      },
      {
        path: 'art-list4', // 防疫手册
        component: () => import('@/views/article/artList4')
      }
    ]
  },
  {
    path: '/reg',
    component: () => import('@/views/register')
    // webpack提供import函数来路由懒加载导入组件
    // 路由懒加载：页面路由路径切换到/reg，才去加载对应组件代码
  }, {
    path: '/login',
    component: () => import('@/views/login')
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/reg'] // 白名单：无需登录可以访问的路由地址

// 全局前置路由守卫 :换账号重新请求用户数据
router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (token) {
    // 登陆了
    if (!store.state.uesrInfo?.uesrname) {
      // 本地有token值，才去请求用户信息
      store.dispatch('gerUserInfoActions')
    }
    next()
  } else {
    // 未登录:强制切换
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 强制打回到登录页
      next('/login')
    }
  }
})

export default router
